//
//  CTFinanceTransformOutVC.m
//  digitalCurrency
//
//  Created by apple on 2019/6/12.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CTFinanceTransformOutVC.h"
#import "CETransformCell.h"
#import "CETransformBottomCell.h"
#import "WCQRCodeVC.h"
#import "MineNetManager.h"
#import "HomeNetManager.h"
#import "AccountSettingInfoModel.h"
#import "CECaptialSettingVC.h"
#import "CTRechargeRecordModel.h"
#import "LYEmptyView.h"
#import "CTFinanceTransformOutListVC.h"
#import "JHUIAlertView.h"

@interface CTFinanceTransformOutVC ()

@property (nonatomic, strong) UITextField *amountTextField;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UILabel *tipsLabel;

@property (nonatomic, strong) JHUIAlertView *alertView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) AccountSettingInfoModel *accountInfo;

@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) NSTimer *numberTimer;
@property (nonatomic, assign) NSInteger timeCount;
@end

@implementation CTFinanceTransformOutVC

- (void)viewDidDsappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [self.numberTimer invalidate];
    self.numberTimer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewTitle.text = LocalizationKey(@"Transfer-out");
    
//    [self rightButton];
    [self.view addSubview:self.tableView];
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.rowHeight = 80;
    [self.tableView registerClass:[CETransformCell class] forCellReuseIdentifier:@"litcell"];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.frame = self.view.bounds;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self accountSettingData];
}

-(void)rightButton {
    UIButton * issueButton = [UIButton buttonWithType:UIButtonTypeSystem];
    issueButton.frame = CGRectMake(0, 0, 80, 24);
    issueButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [issueButton setTitle:LocalizationKey(@"Roll-out list")
                 forState:UIControlStateNormal];
    issueButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, -15);

    [issueButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [issueButton addTarget:self action:@selector(RighttouchEvent) forControlEvents:UIControlEventTouchUpInside];
    //添加到导航条
    UIBarButtonItem *leftBarButtomItem = [[UIBarButtonItem alloc]initWithCustomView:issueButton];
    self.navigationItem.rightBarButtonItem = leftBarButtomItem;
}

- (void)RighttouchEvent {
    CTFinanceTransformOutListVC *vc = [[CTFinanceTransformOutListVC alloc] init];
    vc.unit = self.unit;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)closeView {
    [self.alertView dismiss];
    [self.view endEditing:YES];
    self.textField.text = @"";
}

- (void)confirmClick {
    NSLog(@"confirmClick");
    kPreventRepeatClickTime(1);
    
    NSString *amont = self.amountTextField.text;
    if (amont.length == 0) {
        return;
    }
    if ([amont floatValue] <= 0) {
        return;
    }
    [self.view endEditing:YES];
    
    if ([self.accountInfo.fundsVerified integerValue] == 0) {
        [self.view makeToast:LocalizationKey(@"setMoneyPassword") duration:1.5 position:CSToastPositionCenter];
        CECaptialSettingVC *setvc = [[CECaptialSettingVC alloc] init];
        [self.navigationController pushViewController:setvc animated:YES];
    }
    else {
        JHUIAlertConfig *config = [[JHUIAlertConfig alloc] init];
        config.title.text  = LocalizationKey(@"pinputPwd");
        config.title.color = [UIColor colorWithHEX:maincolor];
        config.title.bottomPadding = 100;
        config.dismissWhenTapOut   = NO;
        config.contentViewWidth    = SCREEN_WIDTH*0.8;
        config.contentViewHeight   = 180+80;
        self.alertView = [[JHUIAlertView alloc] initWithConfig:config];
                
        __weak typeof(self)weakself = self;
        [self.alertView addCustomView:^(JHUIAlertView *alertView, CGRect contentViewRect, CGRect titleLabelRect, CGRect contentLabelRect) {
                    
            UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
            closebtn.tintColor = [UIColor blackColor];
            [closebtn setImage:[UIImage imageNamed:@"loginClose"] forState:UIControlStateNormal];
            [closebtn addTarget:weakself action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
            closebtn.frame = CGRectMake(contentViewRect.size.width-30, 10, 20, 20);
            [alertView.contentView addSubview:closebtn];
                    
            UIView *textBgView = [[UIView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-30, 44)];
                    textBgView.backgroundColor = kColor(@"EAEAEA");
            [alertView.contentView addSubview:textBgView];
            textBgView.layer.cornerRadius = 5;
            textBgView.layer.masksToBounds = YES;
            
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-44, 44)];
            textField.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
            textField.layer.cornerRadius = 5;
            textField.secureTextEntry =YES;
            textField.placeholder = LocalizationKey(@"inputMoneyPassword");
            [alertView.contentView addSubview:textField];
            weakself.textField = textField;
                    
            UIView *codeBgView = [[UIView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+88, contentViewRect.size.width-30, 44)];
            codeBgView.backgroundColor = kColor(@"EAEAEA");
            [alertView.contentView addSubview:codeBgView];
            codeBgView.layer.cornerRadius = 5;
            codeBgView.layer.masksToBounds = YES;
                    
            UITextField *codeTF = [[UITextField alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(titleLabelRect)+88, contentViewRect.size.width-44-80, 44)];
            codeTF.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
            codeTF.layer.cornerRadius = 5;
            codeTF.keyboardType = UIKeyboardTypeNumberPad;
            codeTF.placeholder = LocalizationKey(@"Please enter SMS verification code");
            [alertView.contentView addSubview:codeTF];
            weakself.codeTF = codeTF;
                    
            weakself.codeBtn = [[UIButton alloc]initWithFrame:CGRectMake(contentViewRect.size.width-35-80, CGRectGetMaxY(titleLabelRect)+88, 80, 44)];
            weakself.codeBtn.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
            weakself.codeBtn.layer.cornerRadius = 5;
            [alertView.contentView addSubview:weakself.codeBtn];
            [weakself.codeBtn setTitle:LocalizationKey(@"Get verification code") forState:UIControlStateNormal];
            [weakself.codeBtn setTitleColor:[UIColor colorWithHEX:maincolor] forState:UIControlStateNormal];
            weakself.codeBtn.titleLabel.font = kFont(13);
            [weakself.codeBtn addTarget:weakself action:@selector(codeBtnAct) forControlEvents:UIControlEventTouchUpInside];
            [weakself.codeBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
                    
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(15, CGRectGetMaxY(textField.frame)+88, contentViewRect.size.width-30, 44);
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitle:LocalizationKey(@"Confirm") forState:0];
        [button setTitleColor:[UIColor whiteColor] forState:0];
        button.layer.cornerRadius = 5;
        button.backgroundColor = [UIColor colorWithHEX:maincolor];
        [button addTarget:weakself action:@selector(submitAll) forControlEvents:1<<6];
        [alertView.contentView addSubview:button];
        }];
                
        [self.view addSubview:self.alertView];
    }
}

- (void)codeBtnAct{
  
    self.timeCount = 60;
    self.numberTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(numberTimerAct) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.numberTimer forMode:NSDefaultRunLoopMode];
    self.codeBtn.userInteractionEnabled = NO;
    
    [self getphonncode];
}

- (void)numberTimerAct{
    
    if (self.timeCount == 1) {
        [self.numberTimer invalidate];
        self.numberTimer = nil;
        
        [self.codeBtn setTitle:LocalizationKey(@"Get verification code") forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = YES;
        return;
    }
    
    self.timeCount -- ;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"%.2lds",self.timeCount] forState:UIControlStateNormal];
}

//获取手机验证码
-(void)getphonncode {
     [MineNetManager resetMoneyPasswordCodeForCompleteHandle:^(id resPonseObj, int code) {
           [EasyShowLodingView hidenLoding];
           NSInteger codeint = [resPonseObj[@"code"] integerValue];
           if (code) {
               if (codeint == 0) {
               }
           }
     }];
}

- (void)submitAll {
    NSString *code = self.codeTF.text;
    NSString *pwd = self.textField.text;
    NSString *amont = self.amountTextField.text;

   if (pwd.length == 0) {
       [self.view makeToast:LocalizationKey(@"inputMoneyPassword") duration:1.5 position:CSToastPositionCenter];
       return;
   }
   if (code.length == 0) {
       [self.view makeToast:LocalizationKey(@"inputCode") duration:1.5 position:CSToastPositionCenter];
       return;
   }
    __weak typeof(self)weakself = self;
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    NSDictionary *dic = @{@"coinId":self.unit,@"amount":amont,@"jyPassword":self.textField.text,@"code":code};
    [HomeNetManager doFinancingsDrawoutWithInfo:dic CompleteHandle:^(id resPonseObj, int code) {
        
        weakself.amountTextField.text = @"";
        [EasyShowLodingView hidenLoding];
        NSLog(@"resPonseObj:%@",resPonseObj);
        NSInteger codeInt = [resPonseObj[@"code"] integerValue];
        if (code) {
            if (codeInt == 0) {
                
                [[NSUserDefaults standardUserDefaults] setObject:amont forKey:@"financeCnt"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakself.navigationController popViewControllerAnimated:YES];
                });
            }
            else if (codeInt == -1000001){
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [weakself.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"noNetworkStatus" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

//MARK:--账号设置的状态信息获取
-(void)accountSettingData {
    
    __weak typeof(self)weakself = self;
    [MineNetManager accountSettingInfoForCompleteHandle:^(id resPonseObj, int code) {
        NSInteger rescode = [resPonseObj[@"code"] integerValue];
        if (code) {
            if (rescode == 0) {
               if ([[NSString stringWithFormat:@"%@",resPonseObj[@"data"][@"result"]] isEqualToString:@"0"]) {
                    self.accountInfo = [AccountSettingInfoModel mj_objectWithKeyValues:@{@"fundsVerified":@"0"}];
                }
                else{
                    self.accountInfo = [AccountSettingInfoModel mj_objectWithKeyValues:@{@"fundsVerified":@"1"}];
                }
            }
            else if (rescode == 4000){
                [weakself showLoginViewController];
            }
            else {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [weakself.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"noNetworkStatus" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CETransformCell *cell = [CETransformCell createTableView:tableView];
    self.amountTextField = cell.textField;
    cell.textField.placeholder = [NSString stringWithFormat:@"%@: %@",LocalizationKey(@"Can be Rollof"),self.financingCnt];
    
    [cell.scanbtn setTitle:LocalizationKey(@"All") forState:UIControlStateNormal];
    [cell.scanbtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    @weakify(self);
    [[cell.scanbtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        kPreventRepeatClickTime(1);
        self.amountTextField.text = self.financingCnt;
    }];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return self.footView;
}

- (UIView *)footView {
    if (!_footView) {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        _footView.backgroundColor = [UIColor whiteColor];
        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        confirmBtn.layer.cornerRadius = 5;
        confirmBtn.backgroundColor = [UIColor colorWithHEX:maincolor];
        [confirmBtn setTitle:LocalizationKey(@"Confirm") forState:UIControlStateNormal];
        [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        confirmBtn.titleLabel.font = kFont(18);
        confirmBtn.frame = CGRectMake(23, 56, SCREEN_WIDTH-46, 44);
        [confirmBtn addTarget:self action:@selector(confirmClick) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:confirmBtn];
    }
    
    return _footView;
}

-(void)dealloc{
    NSLog(@"%s",__func__);
}


@end
